package com.qf.listen;

import com.qf.dao.repository.QfOrderRepository;
import com.qf.pojo.dto.QfOrder;
import com.qf.utils.EmailUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Component
public class RabbitListen {

    private static Logger logger = LoggerFactory.getLogger(RabbitListen.class);

    @Autowired
    EmailUtils emailUtils;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    QfOrderRepository qfOrderRepository;

    @RabbitListener(queues = "qf-live-email-queue")
    public void emailListen(String msg){
        logger.debug("从rabbitmq中监听的消息为{}"+msg);
        String code = emailUtils.sendMail(msg);
        logger.debug("发送邮件的内容为{}"+code);
        //存储进入redis中
        redisTemplate.opsForValue().set(msg,code);
        //设置5分钟的过期时间
        redisTemplate.expire(msg,5, TimeUnit.MINUTES);
    }

    @RabbitListener(queues = "pay-queue")
    public void payListen(String orderid){
        logger.debug("从rabbitmq中监听的订单编号为：{}"+orderid);
        //使用orderid查找该订单，并判断该订单的状态 如果还是正在支付状态，则直接置为取消支付
        Optional<QfOrder> byId = qfOrderRepository.findById(orderid);
        if (byId.isPresent()){
            //确认支付状态
            QfOrder qfOrder = byId.get();
            if (qfOrder.getOrderStatus()==3){
                logger.debug("订单编号为{}"+orderid+"到支付时间未支付，置为取消支付");
                qfOrder.setOrderStatus(4);
                qfOrderRepository.saveAndFlush(qfOrder);
            }
        }
    }
}
